package cn.com.jenson.util;

import cn.com.jenson.dao.user.vo.UserVo;
import cn.com.jenson.entity.user.User;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

/**
 * 缓存工具类
 */
public class JWTUtil {

    private static final String secretKey = "jenson";

    /**
     * 获取token
     * @param userVo 用户
     * @return token
     */
    public static String getToken(UserVo userVo) {

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) + 2);

        return JWT.create()
                .withClaim("userId", userVo.getId())
                .withClaim("timeState", calendar.getTimeInMillis())
                .sign(Algorithm.HMAC256(secretKey));
    }

    /**
     * 通过token查询用户
     * @param token token
     * @return HashMap(string,string)
     */
    public static HashMap<String, String> getContext(String token) {
        HashMap<String, String> hashMap = new HashMap<>();
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(secretKey))
                .build()
                .verify(token);
        hashMap.put("userId", verify.getClaim("userId").asInt().toString());
        hashMap.put("timeState", verify.getClaim("timeState").asLong().toString());
        return hashMap;

    }
}
